const cheerio = require('cheerio');
const _ = require('underscore');
const Base = require('./_base')
const path = window.require('path');
const md5 = require('js-md5');

export default class Gather extends Base{
  constructor(reportCb) {
    super(reportCb);
    this.enterurl = 'https://aldenparkes.com/'
    this.pathname = path.resolve('data/' + md5(this.enterurl))
  }
  getProductUrls = async() => {
    let res = await fetch(this.enterurl).then(res => res.text());
    let $ = cheerio.load(res)
    var html = $('#menu-item-123').html();
    let urls = []
    if ($("ul.sub-menu", html).length < 1 || $("ul.sub-menu", html) === undefined)
      return false;
    $('ul.sub-menu', html).children().each(function(i, e) {
      if ($('li', $(this).html()) === undefined || $('li', $(this).html()).length < 1)
        return false;
      $('li', $(this).html()).each(function(j, el) {
        if ($('a', $(this).html()).eq(0).attr('href') === undefined)
          return false;
        urls.push($('a', $(this).html()).eq(0).attr('href'));
      });
    });
    let rurls = []
    for (let i of _.range(urls.slice(0,4).length)) {
      let url = urls[i]
      this.status.msg = '获取列表'
      this.status.current = i + 1
      this.status.count = urls.length
      this.reportCb(this.status)
      console.log('fetch list', url)
      let res = await fetch(url).then(res => res.text());
      let $ = cheerio.load(res)
      let goods_list = $('.fusion-portfolio-wrapper').html();
      if ($("article", goods_list).length < 1 || $("article", goods_list) === undefined)
        continue
      $('article', goods_list).each(function(i, e) {
        if ($('.fusion-image-wrapper a', $(this).html()).eq(0) === undefined)
          return false;
        let url = $('.fusion-image-wrapper a', $(this).html()).eq(0).attr('href')
        console.log('add ', url)
        rurls.push(url)
      });
    }
    return rurls
  }
  getProduct = async(url) => {
    console.log('fetch product', url)
    let res = await fetch(url).then(res => res.text());
    let $ = cheerio.load(res)
    // 获取商品的详细地址
    var product = {};
    let good = $('#main').html();
    // product.origin_html=$('html').html();
    product.origin_url = url;
    product.brand_num = 'aldenparkes';
    product.name = $('h1.entry-title').eq(0).text();
    product.date = new Date().getTime();
    product.description = $('.project-description p', good).eq(0).text() || '';
    product.images = [];
    product.path = [];
    product.local_path = [];
    if ($('.slides', good) === undefined || $('.slides li', good).length < 1)
      return false;

    $('.slides li', good).each((j, el)=> {
      if ($('img', $(this).html()).eq(0).attr('src') === undefined)
        return false;
      let img = $('img', $(this).html()).eq(0).attr('src');

      if(!img.startsWith('http:')) img = 'http:'+img
      product.images.push({"pic_url": img});
    });

    return product
  }
}
